"""Tests the app module"""

import StringIO
import unittest
import yaml
from gaweb.master import app
from gaweb.master import helpers


def _make_opener(contents):
    def opener(*args, **kwargs):
        return StringIO.StringIO(contents)
    return opener


class TestReadConfig(unittest.TestCase):
    GOOD_CONFIG = {'logging': 'debug',
                   'nodes': [{'address': 'localhost'}]}

    def test_good_config_yaml(self):
        in_config = self.GOOD_CONFIG
        opener = _make_opener(yaml.dump(in_config))
        out_config = helpers.read_config(opener=opener)

        self.assertEqual(in_config, out_config)

    def test_bad_config_yaml(self):
        opener = _make_opener(']]]]')
        self.assertRaises(yaml.parser.ParserError,
                          helpers.read_config, opener=opener)
        
    def test_bad_fname(self):
        def opener(*args, **kwargs):
            raise IOError()
        self.assertRaises(IOError,
                          helpers.read_config, opener=opener)


class RandomStrTest(unittest.TestCase):

    def test_is_basestring(self):
        s = helpers.random_str(8)
        self.assertTrue(isinstance(s, basestring))

    def test_len(self):
        for n in [0, 2, 4, 8, 16, 32]:
            s = helpers.random_str(n)
            self.assertEqual(len(s), n)

    def test_negative_n(self):
        for n in [-1, -2, -8, -16, -32]:
            self.assertRaises(ValueError, helpers.random_str, n)


if __name__ == '__main__':
    unittest.main()
    
